package com.bungarus.busi;

import com.bungarus.Access;
import com.bungarus.event.SessionCreatedEvent;
import com.bungarus.event.SessionTransferedEvent;
import com.bungarus.model.MessageBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

/**
 *
 * Created by tang on 2018/11/13.
 */
public class TransferSessionHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(TransferSessionHandler.class);
    private final Access access;

    public TransferSessionHandler(Access access) {
        this.access = access;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof SessionCreatedEvent){
            SessionCreatedEvent event = (SessionCreatedEvent) evt;
            //send session info to transfer layer
            InnerClient client = access.getInnerClientConnectingToBackendClusterNode(Access.CLUSTER_TAG_TRANSFER);
            client.sendMessage(MessageBuilder.buildSessionMessage(event.getSession()),
                    Access.CLUSTER_TAG_TRANSFER);
            logger.debug("===================== access to transfer");
            ctx.fireUserEventTriggered(new SessionTransferedEvent(event.getSession()));
        }
        else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
